//
//  RegisterViewController.swift
//  ddx0513
//
//  Created by ejian  on 15/6/1.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

class RegisterViewController: UIViewController {
    var cellphone: String = ""
    var secondCountDown = 60
    var countDownTimer: NSTimer?
    var sourceNavi = true
    var hud: MBProgressHUD?
    var password: String?
    var code: String?

    @IBOutlet weak var phoneLabel: UILabel!
    @IBOutlet weak var timeCountingLabel: UILabel!
    @IBOutlet weak var resendLabel: UILabel!
    @IBOutlet weak var codeTextField: UITextField!
    @IBOutlet weak var pwdTextField: UITextField!
        
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        //发送短信验证码
        sendSmsCode()
        
        var length = count(cellphone)
        if (length == 11) {
            var str = cellphone
            str = StringUtils.insertAtIndex(" ", toString: str, atIndex: 3)
            str = StringUtils.insertAtIndex(" ", toString: str, atIndex: 8)
            self.phoneLabel.text = str
        }
        self.resendLabel.hidden = true
        
        self.timeCountingLabel.text = "重发(\(secondCountDown)秒)"
        countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timeFireMethod"), userInfo: nil, repeats: true)
        var resendTapGesture = UITapGestureRecognizer(target: self, action: Selector("resendLabelTapped:"))
        resendLabel.addGestureRecognizer(resendTapGesture)
        
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func sendSmsCode() {
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLSendCode(), parameters: ["mobile": cellphone, "sendtype": "1"], responseHandler: nil, netErrorHandler: nil, successHandler: sendSmsCodeHandler, interErrorHandler: nil, jsonErrorHandler: nil)
    }
    
    func setNavi() {
        if (sourceNavi) {
            self.navigationController?.setNavigationBarHidden(true, animated: true)
        } else {
            self.navigationController?.setNavigationBarHidden(false, animated: true)
        }
    }
    
    @IBAction func backButtonPressed(sender: AnyObject) {
        self.navigationController?.popViewControllerAnimated(true)
        setNavi()
    }
    
    @IBAction func okButtonPressed(sender: AnyObject) {
        if (self.codeTextField.text == "") {
            MBHudUtils.showText("请输入短信验证码", view: self.view)
            return
        } else if (self.pwdTextField.text == "") {
            MBHudUtils.showText("请输入登录密码", view: self.view)
            return
        }
        
        startIndicator()
        password = self.pwdTextField.text
        code = self.codeTextField.text
        let a = ["mobile": cellphone, "pwd": password!, "code": code!, "push_alias": cellphone]
        NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLRegister(), parameters: a, view: self.view, responseHandler: stopIndicator, successHandler: register)
    }
    
    func resendLabelTapped(sender: UILabel) -> Void {
        sendSmsCode()
        self.timeCountingLabel.text = "重发(\(secondCountDown)秒)"
        self.resendLabel.hidden = true
        self.timeCountingLabel.hidden = false
        countDownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timeFireMethod"), userInfo: nil, repeats: true)
    }
    
    func timeFireMethod() -> Void {
        secondCountDown--
        if (secondCountDown > 0) {
            self.timeCountingLabel.text = "重发(\(secondCountDown)秒)"
        } else {
            self.timeCountingLabel.hidden = true
            self.resendLabel.hidden = false
            countDownTimer!.invalidate()
        }
    }
    
    //MARK: - 网络回调函数
    
    func startIndicator() {
        hud = MBProgressHUD(view: self.view)
        self.view.addSubview(hud!)
        hud?.labelText = "注册中.."
        hud?.show(true)
    }
    
    func stopIndicator() {
        hud?.hide(false)
    }
    
    func register(json: JSON) {
        var userId = json["userid"].int
        var imUsername = json["im_username"].string
        var imPassword = json["im_password"].string
        var vipType = json["vip_type"].string
        var vipBegin = json["vip_begin"].int64
        var vipExpire = json["vip_expire"].int64
        var token = json["token"].string
        
        var userDefault = NSUserDefaults.standardUserDefaults()
        userDefault.setObject(cellphone, forKey: DBUtils.varNames.loginName)
        userDefault.setObject(password, forKey: DBUtils.varNames.password)
        userDefault.setObject(true, forKey: DBUtils.varNames.loginStatus)
        userDefault.synchronize()
        
        if let a = userId {
            DBUtils.mem.userId = a
        }
        DBUtils.mem.pushAlias = cellphone
        if let a = imUsername {
            DBUtils.mem.imUsername = a
        }
        if let a = imPassword {
            DBUtils.mem.imPassword = a
        }
        if let a = token {
            DBUtils.mem.token = a
        }
        if let a = vipType {
            DBUtils.mem.vipType = a
        }
        if let a = vipBegin {
            DBUtils.mem.vipBegin = a
        }
        if let a = vipExpire {
            DBUtils.mem.vipExpire = a
        }
        
        DBUtils.mem.loginStatus = true
        
        rootController.navigationController?.popToRootViewControllerAnimated(true)
        rootController.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    func sendSmsCodeHandler(json: JSON) {
        if let resendTime = json["resendtime"].int {
            secondCountDown = resendTime
        }
        var code = json["code"].string
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
